package org.example.compare.schedule;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.example.compare.dto.*;
import org.example.compare.global.SchData;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 测试数据生成器类，用于为calculateItem_2函数生成测试数据
 * 该函数使用到的非函数参数列表外部变量包括:
 * 1. SchData.hParamSet 中的 "NormalPeriodHour" 参数
 * 2. hProcessSet - 需要进行排产的工序集
 * 3. sPositionsScore - 可以排产的工位
 * 4. hScoreByProcess - 按工序查找的分数表
 */
public class CalculateItem2TestDataGenerator {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Random random = new Random();

    static {
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 生成随机测试数据并保存到文件
     */
    public static void generateRandomTestData(int iteration) throws IOException {
        String basePath = "../../test_data/calculateItem_2/random_case_" + iteration;
        File baseDir = new File(basePath);

        // 清空文件夹
        clearDirectory(baseDir);

        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }

        // 生成测试数据
        generateSysParamData(basePath);
        Map<Long, OrderProcess> hProcessSet = generateProcessSetData(basePath);
        Set<Long> sPositionsScore = generatePositionScoreData(basePath);
        generateScoreByProcessData(basePath, hProcessSet, sPositionsScore);
        generateFunctionParams(basePath);
        // 生成订单数据
        generateOrderId2Order(basePath, hProcessSet);
    }

    /**
     * 生成手动测试数据并保存到文件
     */
    public static void generateManualTestData(int caseNumber) throws IOException {
        String basePath = "../../test_data/calculateItem_2/manual_case_" + caseNumber;
        File baseDir = new File(basePath);

        // 清空文件夹
        clearDirectory(baseDir);

        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }

        if (caseNumber == 1) {
            generateManualTestCase1(basePath);
        } else if (caseNumber == 2) {
            generateManualTestCase2(basePath);
        }
    }

    /**
     * 生成手动测试案例1
     */
    private static void generateManualTestCase1(String basePath) throws IOException {
        // 创建测试用的系统参数
        Map<String, SysParam> hParamSet = new HashMap<>();

        // NormalPeriodHour 参数 - 固定值 8
        SysParam normalPeriodHour = new SysParam();
        normalPeriodHour.setParamId(3001L);
        normalPeriodHour.setParamCode("NormalPeriodHour");
        normalPeriodHour.setParamName("正常工时");
        normalPeriodHour.setParamDefaultValue("8");
        normalPeriodHour.setEffective(true);
        hParamSet.put("NormalPeriodHour", normalPeriodHour);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hParamSet.json"), hParamSet);

        // 生成工序集数据
        Map<Long, OrderProcess> hProcessSet = new HashMap<>();

        // 创建测试用的订单数据
        OrderDto orderDto = OrderDto.InitOrder();
        orderDto.setMLocalOrderNum("TEST3001123456");
        orderDto.setMiTotalPlanCnt(1000);
        orderDto.setMiNow2DeadlineSecs(86400); // 1天 = 24小时

        // 工序1
        OrderProcess process1 = OrderProcess.InitOrderProcess(orderDto);
        process1.setOrderProcessId(3001L);
        process1.setMfProcessTotalTime(120.0f); // 2分钟标准工时
        process1.setMiFinishedCnt(200);
        process1.setMiPartSeqNum(1);
        process1.setMPartId(300L);

        ProcessSch scheduling1 = new ProcessSch();
        scheduling1.setMbHoldFlag(false);
        scheduling1.setMbNGFlag(false);
        scheduling1.setMbAllUnDoInLib(true);
        scheduling1.setMNowHourTarget(50); // 当前小时任务数

        process1.setMScheduling(scheduling1);
        hProcessSet.put(3001L, process1);

        // 工序2
        OrderProcess process2 = OrderProcess.InitOrderProcess(orderDto);
        process2.setOrderProcessId(3002L);
        process2.setMfProcessTotalTime(180.0f); // 3分钟标准工时
        process2.setMiFinishedCnt(150);
        process2.setMiPartSeqNum(2);
        process2.setMPartId(300L);

        ProcessSch scheduling2 = new ProcessSch();
        scheduling2.setMbHoldFlag(false);
        scheduling2.setMbNGFlag(false);
        scheduling2.setMbAllUnDoInLib(true);
        scheduling2.setMNowHourTarget(30); // 当前小时任务数

        process2.setMScheduling(scheduling2);
        hProcessSet.put(3002L, process2);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hProcessSet.json"), hProcessSet);

        // 生成可以排产的工位数据
        Set<Long> sPositionsScore = new HashSet<>();
        sPositionsScore.add(30001L);
        sPositionsScore.add(30002L);
        sPositionsScore.add(30003L);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/sPositionsScore.json"), sPositionsScore);

        // 生成按工序查找的分数表数据
        Map<Long, List<Score>> hScoreByProcess = new HashMap<>();

        // 工序1的分数
        List<Score> scores1 = new ArrayList<>();
        Score score1_1 = new Score();
        score1_1.setPositionId(30001L);
        score1_1.setTotal(80.0);
        double[] scoreItems1 = new double[20];
        for (int i = 0; i < scoreItems1.length; i++) {
            scoreItems1[i] = 5.0;
        }
        score1_1.setScoreItem(scoreItems1);
        scores1.add(score1_1);

        Score score1_2 = new Score();
        score1_2.setPositionId(30002L);
        score1_2.setTotal(75.0);
        double[] scoreItems2 = new double[20];
        for (int i = 0; i < scoreItems2.length; i++) {
            scoreItems2[i] = 4.5;
        }
        score1_2.setScoreItem(scoreItems2);
        scores1.add(score1_2);

        hScoreByProcess.put(3001L, scores1);

        // 工序2的分数
        List<Score> scores2 = new ArrayList<>();
        Score score2_1 = new Score();
        score2_1.setPositionId(30002L);
        score2_1.setTotal(85.0);
        double[] scoreItems3 = new double[20];
        for (int i = 0; i < scoreItems3.length; i++) {
            scoreItems3[i] = 6.0;
        }
        score2_1.setScoreItem(scoreItems3);
        scores2.add(score2_1);

        Score score2_2 = new Score();
        score2_2.setPositionId(30003L);
        score2_2.setTotal(70.0);
        double[] scoreItems4 = new double[20];
        for (int i = 0; i < scoreItems4.length; i++) {
            scoreItems4[i] = 4.0;
        }
        score2_2.setScoreItem(scoreItems4);
        scores2.add(score2_2);

        hScoreByProcess.put(3002L, scores2);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hScoreByProcess.json"), hScoreByProcess);

        // 生成函数参数
        Map<String, Object> functionParams = new HashMap<>();
        functionParams.put("ratio", 0.08);
        objectMapper.writeValue(new File(basePath + "/testCases.json"), functionParams);
        
        // 生成订单映射数据
        Map<String, OrderDto> orderId2Order = new HashMap<>();
        orderId2Order.put("TEST3001123456", orderDto);
        objectMapper.writeValue(new File(basePath + "/orderId2Order.json"), orderId2Order);
    }

    /**
     * 生成手动测试案例2
     */
    private static void generateManualTestCase2(String basePath) throws IOException {
        // 创建测试用的系统参数
        Map<String, SysParam> hParamSet = new HashMap<>();

        // NormalPeriodHour 参数 - 固定值 10
        SysParam normalPeriodHour = new SysParam();
        normalPeriodHour.setParamId(3002L);
        normalPeriodHour.setParamCode("NormalPeriodHour");
        normalPeriodHour.setParamName("正常工时");
        normalPeriodHour.setParamDefaultValue("10");
        normalPeriodHour.setEffective(true);
        hParamSet.put("NormalPeriodHour", normalPeriodHour);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hParamSet.json"), hParamSet);

        // 生成工序集数据
        Map<Long, OrderProcess> hProcessSet = new HashMap<>();

        // 创建测试用的订单数据
        OrderDto orderDto = OrderDto.InitOrder();
        orderDto.setMLocalOrderNum("TEST3002789012");
        orderDto.setMiTotalPlanCnt(800);
        orderDto.setMiNow2DeadlineSecs(172800); // 2天 = 48小时

        // 工序1
        OrderProcess process1 = OrderProcess.InitOrderProcess(orderDto);
        process1.setOrderProcessId(4001L);
        process1.setMfProcessTotalTime(90.0f); // 1.5分钟标准工时
        process1.setMiFinishedCnt(100);
        process1.setMiPartSeqNum(1);
        process1.setMPartId(400L);

        ProcessSch scheduling1 = new ProcessSch();
        scheduling1.setMbHoldFlag(false);
        scheduling1.setMbNGFlag(false);
        scheduling1.setMbAllUnDoInLib(true);
        scheduling1.setMNowHourTarget(40); // 当前小时任务数

        process1.setMScheduling(scheduling1);
        hProcessSet.put(4001L, process1);

        // 工序2
        OrderProcess process2 = OrderProcess.InitOrderProcess(orderDto);
        process2.setOrderProcessId(4002L);
        process2.setMfProcessTotalTime(150.0f); // 2.5分钟标准工时
        process2.setMiFinishedCnt(50);
        process2.setMiPartSeqNum(2);
        process2.setMPartId(400L);

        ProcessSch scheduling2 = new ProcessSch();
        scheduling2.setMbHoldFlag(true); // 挂起状态
        scheduling2.setMbNGFlag(false);
        scheduling2.setMbAllUnDoInLib(true);
        scheduling2.setMNowHourTarget(25); // 当前小时任务数

        process2.setMScheduling(scheduling2);
        hProcessSet.put(4002L, process2);

        // 工序3
        OrderProcess process3 = OrderProcess.InitOrderProcess(orderDto);
        process3.setOrderProcessId(4003L);
        process3.setMfProcessTotalTime(200.0f); // 约3.3分钟标准工时
        process3.setMiFinishedCnt(75);
        process3.setMiPartSeqNum(3);
        process3.setMPartId(400L);

        ProcessSch scheduling3 = new ProcessSch();
        scheduling3.setMbHoldFlag(false);
        scheduling3.setMbNGFlag(false);
        scheduling3.setMbAllUnDoInLib(false); // 不是全部未做在库
        scheduling3.setMNowHourTarget(35); // 当前小时任务数

        process3.setMScheduling(scheduling3);
        hProcessSet.put(4003L, process3);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hProcessSet.json"), hProcessSet);

        // 生成可以排产的工位数据
        Set<Long> sPositionsScore = new HashSet<>();
        sPositionsScore.add(40001L);
        sPositionsScore.add(40002L);
        sPositionsScore.add(40003L);
        sPositionsScore.add(40004L);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/sPositionsScore.json"), sPositionsScore);

        // 生成按工序查找的分数表数据
        Map<Long, List<Score>> hScoreByProcess = new HashMap<>();

        // 工序1的分数
        List<Score> scores1 = new ArrayList<>();
        Score score1_1 = new Score();
        score1_1.setPositionId(40001L);
        score1_1.setTotal(90.0);
        double[] scoreItems1 = new double[20];
        for (int i = 0; i < scoreItems1.length; i++) {
            scoreItems1[i] = 7.0;
        }
        score1_1.setScoreItem(scoreItems1);
        scores1.add(score1_1);

        Score score1_2 = new Score();
        score1_2.setPositionId(40002L);
        score1_2.setTotal(85.0);
        double[] scoreItems2 = new double[20];
        for (int i = 0; i < scoreItems2.length; i++) {
            scoreItems2[i] = 6.5;
        }
        score1_2.setScoreItem(scoreItems2);
        scores1.add(score1_2);

        hScoreByProcess.put(4001L, scores1);

        // 工序2的分数 (挂起状态)
        List<Score> scores2 = new ArrayList<>();
        Score score2_1 = new Score();
        score2_1.setPositionId(40002L);
        score2_1.setTotal(80.0);
        double[] scoreItems3 = new double[20];
        for (int i = 0; i < scoreItems3.length; i++) {
            scoreItems3[i] = 5.0;
        }
        score2_1.setScoreItem(scoreItems3);
        scores2.add(score2_1);

        hScoreByProcess.put(4002L, scores2);

        // 工序3的分数 (不是全部未做在库)
        List<Score> scores3 = new ArrayList<>();
        Score score3_1 = new Score();
        score3_1.setPositionId(40003L);
        score3_1.setTotal(70.0);
        double[] scoreItems4 = new double[20];
        for (int i = 0; i < scoreItems4.length; i++) {
            scoreItems4[i] = 4.0;
        }
        score3_1.setScoreItem(scoreItems4);
        scores3.add(score3_1);

        Score score3_2 = new Score();
        score3_2.setPositionId(40004L);
        score3_2.setTotal(65.0);
        double[] scoreItems5 = new double[20];
        for (int i = 0; i < scoreItems5.length; i++) {
            scoreItems5[i] = 3.5;
        }
        score3_2.setScoreItem(scoreItems5);
        scores3.add(score3_2);

        hScoreByProcess.put(4003L, scores3);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hScoreByProcess.json"), hScoreByProcess);

        Map<String, Object> functionParams = new HashMap<>();
        functionParams.put("ratio", 0.05);
        objectMapper.writeValue(new File(basePath + "/testCases.json"), functionParams);
        
        // 生成订单映射数据
        Map<String, OrderDto> orderId2Order = new HashMap<>();
        orderId2Order.put("TEST3002789012", orderDto);
        objectMapper.writeValue(new File(basePath + "/orderId2Order.json"), orderId2Order);
    }

    /**
     * 清空指定目录下的所有文件
     *
     * @param directory 要清空的目录
     * @throws IOException IO异常
     */
    private static void clearDirectory(File directory) throws IOException {
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        Files.delete(file.toPath());
                    }
                }
            }
        }
    }

    /**
     * 生成系统参数数据
     * 包括 NormalPeriodHour 参数
     */
    private static void generateSysParamData(String basePath) throws IOException {
        // 创建测试用的系统参数
        Map<String, SysParam> hParamSet = new HashMap<>();

        // NormalPeriodHour 参数 - 随机值 6-12
        SysParam normalPeriodHour = new SysParam();
        normalPeriodHour.setParamId((long) (3000 + random.nextInt(1000)));
        normalPeriodHour.setParamCode("NormalPeriodHour");
        normalPeriodHour.setParamName("正常工时");
        // 小时数为整数不需要保留小数
        normalPeriodHour.setParamDefaultValue(String.valueOf(6 + random.nextInt(7))); // 6-12小时
        normalPeriodHour.setEffective(true);
        hParamSet.put("NormalPeriodHour", normalPeriodHour);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hParamSet.json"), hParamSet);
    }

    /**
     * 生成工序集数据
     */
    private static Map<Long, OrderProcess> generateProcessSetData(String basePath) throws IOException {
        Map<Long, OrderProcess> hProcessSet = new HashMap<>();

        // 随机生成工序数量 3-8个
        int processCount = 3 + random.nextInt(6);

        // 创建测试用的订单数据
        OrderDto orderDto = OrderDto.InitOrder();
        orderDto.setMLocalOrderNum("TEST" + (3000 + random.nextInt(100)) + "" + (100000 + random.nextInt(900000)));
        orderDto.setMiTotalPlanCnt(500 + random.nextInt(1001)); // 500-1500
        orderDto.setMiNow2DeadlineSecs(random.nextInt(10 * 24 * 3600)); // 0-10天的秒数

        List<Long> processIds = new ArrayList<>();
        for (int i = 0; i < processCount; i++) {
            processIds.add(3000L + i * 10 + random.nextInt(10));
        }

        for (Long processId : processIds) {
            OrderProcess process = OrderProcess.InitOrderProcess(orderDto);
            process.setOrderProcessId(processId);
            // 标准工时保留两位小数
            float processTime = 60.0f + random.nextInt(600);
            processTime = new BigDecimal(processTime).setScale(2, RoundingMode.HALF_UP).floatValue();
            process.setMfProcessTotalTime(processTime); // 60-660秒标准工时
            process.setMiFinishedCnt(random.nextInt(orderDto.getMiTotalPlanCnt()));
            process.setMiPartSeqNum(processIds.indexOf(processId) + 1);
            process.setMPartId((long) (300 + random.nextInt(5))); // 300-304部件ID

            ProcessSch scheduling = new ProcessSch();
            scheduling.setMbHoldFlag(random.nextBoolean());
            scheduling.setMbNGFlag(random.nextBoolean());
            scheduling.setMbAllUnDoInLib(random.nextBoolean());
            scheduling.setMNowHourTarget(10 + random.nextInt(100)); // 10-110的当前小时任务数

            process.setMScheduling(scheduling);
            hProcessSet.put(processId, process);
        }

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hProcessSet.json"), hProcessSet);

        return hProcessSet;
    }

    /**
     * 生成可以排产的工位数据
     */
    private static Set<Long> generatePositionScoreData(String basePath) throws IOException {
        Set<Long> sPositionsScore = new HashSet<>();

        // 随机生成工位数量 5-15个
        int positionCount = 5 + random.nextInt(11);

        // 添加测试工位ID
        for (int i = 0; i < positionCount; i++) {
            sPositionsScore.add((long) (30000 + random.nextInt(90000))); // 30000-119999的工位ID
        }

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/sPositionsScore.json"), sPositionsScore);

        return sPositionsScore;
    }

    /**
     * 生成按工序查找的分数表数据
     */
    private static void generateScoreByProcessData(String basePath, Map<Long, OrderProcess> hProcessSet, Set<Long> sPositionsScore) throws IOException {
        Map<Long, List<Score>> hScoreByProcess = new HashMap<>();

        // 使用已生成的工序ID来创建分数数据
        List<Long> processIds = new ArrayList<>(hProcessSet.keySet());

        for (Long processId : processIds) {
            List<Score> scores = new ArrayList<>();

            // 获取部分工位ID用于这个工序
            List<Long> positionIds = new ArrayList<>(sPositionsScore);
            Collections.shuffle(positionIds); // 随机打乱

            // 每个工序对应1-5个工位分数（不超过工位总数）
            int scoreCount = Math.min(1 + random.nextInt(5), positionIds.size());
            for (int j = 0; j < scoreCount; j++) {
                Score score = new Score();
                score.setPositionId(positionIds.get(j));
                // 总分保留两位小数
                double total = random.nextDouble() * 100; // 0-100的总分
                total = new BigDecimal(total).setScale(2, RoundingMode.HALF_UP).doubleValue();
                score.setTotal(total);

                // 初始化分数项数组，包含随机分数，每项保留两位小数
                double[] scoreItems = new double[20];
                for (int k = 0; k < scoreItems.length; k++) {
                    double item = random.nextDouble() * 50; // 0-50的分数项
                    item = new BigDecimal(item).setScale(2, RoundingMode.HALF_UP).doubleValue();
                    scoreItems[k] = item;
                }
                score.setScoreItem(scoreItems);

                scores.add(score);
            }

            hScoreByProcess.put(processId, scores);
        }

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hScoreByProcess.json"), hScoreByProcess);
    }

    /**
     * 生成函数参数
     */
    private static void generateFunctionParams(String basePath) throws IOException {
        Map<String, Object> functionParams = new HashMap<>();
        // 生成 0.01 到 1.0 之间的随机 ratio 值，保留两位小数
        double randomRatio = 0.01 + random.nextDouble() * 0.99;
        randomRatio = new BigDecimal(randomRatio).setScale(2, RoundingMode.HALF_UP).doubleValue();
        functionParams.put("ratio", randomRatio);
        objectMapper.writeValue(new File(basePath + "/testCases.json"), functionParams);
    }

    /**
     * 生成订单ID到订单对象的映射
     */
    private static void generateOrderId2Order(String basePath, Map<Long, OrderProcess> hProcessSet) throws IOException {
        Map<String, OrderDto> orderId2Order = new HashMap<>();
        
        // 收集所有不同的订单号
        Set<String> orderNums = new HashSet<>();
        for (OrderProcess process : hProcessSet.values()) {
            orderNums.add(process.getMLocalOrderNum());
        }
        
        // 为每个订单号创建一个OrderDto对象
        for (String orderNum : orderNums) {
            OrderDto orderDto = OrderDto.InitOrder();
            orderDto.setMLocalOrderNum(orderNum);
            orderDto.setMiTotalPlanCnt(500 + random.nextInt(1001)); // 500-1500
            orderDto.setMiNow2DeadlineSecs(random.nextInt(10 * 24 * 3600)); // 0-10天的秒数
            orderId2Order.put(orderNum, orderDto);
        }
        
        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/orderId2Order.json"), orderId2Order);
    }

    public static void main(String[] args) {
        try {
            // 确保主目录存在
            File mainDir = new File("../../test_data/calculateItem_2");
            if (!mainDir.exists()) {
                mainDir.mkdirs();
            }

            // 生成50组随机测试数据
            for (int i = 1; i <= 50; i++) {
                generateRandomTestData(i);
                System.out.println("随机测试数据集 " + i + " 已成功生成");
            }

            // 生成2个手动测试案例
            for (int i = 1; i <= 2; i++) {
                generateManualTestData(i);
                System.out.println("手动测试案例 " + i + " 已成功生成");
            }

            System.out.println("所有测试数据已成功生成并保存到../../test_data/calculateItem_2目录下");
        } catch (IOException e) {
            System.err.println("生成测试数据时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}